# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf.urls.defaults import *
from django.template import Context, loader
from django.http import HttpResponse
import urllib2
from xml.dom import minidom
MAX_ITEMS = 10

def index(request):
    t = loader.get_template('index.html');
    
    items =  getRSS("http://www.blogjava.net/rss");
    javaBlogItems = getLatestRssItems(items,MAX_ITEMS);
    
    items =  getRSS("http://feeds.delicious.com/v2/rss/OracleTechnologyNetwork/otntecharticle");
    oracleFeedItems =getLatestRssItems(items,MAX_ITEMS);
    
    #items = getRSS("http://feed.huaidan.org/");
    huaidanItems = None;
    
    items = getRSS("http://www.dbanotes.net/index.xml");
    dbanotesItems = getLatestRssItems(items,MAX_ITEMS);
    
    items = getRSS("http://www.dzone.com/links/feed/frontpage/rss.xml");
    dzoneItems = getLatestRssItems(items,MAX_ITEMS);
    
    items = getRSS("http://feeds.delicious.com/v2/rss/?count=15");
    deliciousItems = getLatestRssItems(items,MAX_ITEMS);
    
    items = getRSS("http://www.lengmo.net/feed.php");
    lengmoItems = getLatestRssItems(items,MAX_ITEMS);
    
    items = getRSS("http://ajaxian.com/index.xml");
    ajaxianItems = getLatestRssItems(items,MAX_ITEMS);
    
    c = Context({'oracleFeedItems':oracleFeedItems,
    'javaBlogItems':javaBlogItems,
    'huaidanItems':huaidanItems,
    'dbanotesItems':dbanotesItems,
    'dzoneItems':dzoneItems,
    'deliciousItems':deliciousItems,
    'lengmoItems':lengmoItems,
    'ajaxianItems':ajaxianItems});    
    
    return HttpResponse(t.render(c))
    
def getRSS(addr):
    xmldoc = minidom.parseString(urllib2.urlopen(addr).read())
    items = xmldoc.getElementsByTagName('item')
    return items

def getAtom(addr):
    xmldoc = minidom.parseString(urllib2.urlopen(addr).read());
    items = xmldoc.getElementsByTagName('item');
    
    return items;

def getLatestAtomItems(items,num):
    pass;

def getLatestRssItems(items, num):
    latest=[]
    inxs = ['title','pubDate','link']
    myitems = [item for index, item in enumerate(items) if index < num]
    for  item in myitems:
        latest.append(dict(zip(inxs,[item.getElementsByTagName(inx)[0].firstChild.data for inx in inxs])))
      
    return latest
